package top.glkj.hms.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import top.glkj.hms.dao.PermissionDao;
import top.glkj.hms.entity.Permission;
import top.glkj.hms.entity.Resource;
import top.glkj.hms.service.PermissionService;
import top.glkj.hms.service.ResourceService;
import top.glkj.hms.utils.*;

import java.util.*;

/**
 * @author : xgl
 * @version : 0.0.1
 * @date :2020/11/16 23:43
 */
@Service
@Slf4j
public class PermissionServiceImpl implements PermissionService {
    private final PermissionDao permissionDao;
    private final ResourceService resourceService;
    @Autowired
    public PermissionServiceImpl(PermissionDao permissionDao,ResourceService resourceService) {
        this.permissionDao = permissionDao;
        this.resourceService = resourceService;
    }

    /**
     * 获取所有用户
     *
     * @return Page<T>
     */
    @Override
    public Result getAll() {
        List<Permission> all = permissionDao.findAll();
        if (all.size() == 0) {
            return ResultFactory.isError(StaticValue.DATA_NOT_FOUND, null);
        } else {
            return ResultFactory.isSuccess(StaticValue.GET_DATA_SUCCESS, all);
        }
    }

    /**
     * 获取所有用户，按分页方式
     *
     * @param id id
     * @return T t
     */
    @Override
    public Result getOne(Long id) {
        Permission permission = permissionDao.findById(id).orElse(null);
        if (permission == null) {
            return ResultFactory.isError(StaticValue.DATA_NOT_FOUND, null);
        } else {
            return ResultFactory.isSuccess(StaticValue.GET_DATA_SUCCESS, permission);
        }
    }

    /**
     * 修改或者保存
     *
     * @param permission T t
     * @return true or false
     */
    @Override
    public Result save(Permission permission) {
        try {
            Permission save = permissionDao.save(permission);
            return ResultFactory.isSuccess(StaticValue.SUCCESS_MESSAGE, save);
        } catch (Exception e) {
            log.error(e.getMessage());
            return ResultFactory.isError(StaticValue.ERROR_MESSAGE, null);
        }
    }

    /**
     * 彻底从数据库中删除实体{T}
     *
     * @param permission T t
     * @return true or false
     */
    @Override
    public Result delete(Permission permission) {
        try {
            permissionDao.delete(permission);
            return ResultFactory.isSuccess(StaticValue.DELETE_DATA_ERROR);
        } catch (Exception e) {
            log.error(e.getMessage());
            return ResultFactory.isError(StaticValue.ERROR_MESSAGE);
        }
    }

    /**
     * 标记删除
     *
     * @param permission T t
     * @return true or false
     */
    @Override
    public Result remove(Permission permission) {
        permission.setDel(true);
        permission.setStatus(Status.Delete);
        Result save = save(permission);
        if (ResultFactory.isSuccess(save)) {
            return ResultFactory.isSuccess(StaticValue.DELETE_DATA_SUCCESS, save);
        } else {
            return ResultFactory.isException(StaticValue.DELETE_DATA_ERROR);
        }
    }

    /**
     * 分页查询
     *
     * @param page 当前页码
     * @param size 页面大小
     * @return page Role
     */
    @Override
    public Result getPermissionsByPageAndSize(int page, int size) {
        GlUtils<Permission, PermissionDao> glUtils = new GlUtils<>();
        return glUtils.getAllByPageAndSize(page,size,permissionDao);

    }

    /**
     * 分页条件查询
     *
     * @param page    当前页码
     * @param size    页面大小
     * @param argName 参数名
     * @param value   参数值
     * @return page User
     */
    @Override
    public Result getAllPermissionsByPageAndSizeAndArgs(int page, int size, String argName, String value) {
        GlUtils<Permission, PermissionDao> glUtils = new GlUtils<>();
        return glUtils.getAllByPageAndSizeAndArgs(page,size,argName,argName,permissionDao);

    }

    /**
     * 分页查询
     *
     * @param page 当前页码
     * @param size 页面大小
     * @param args 参数键值对
     * @return page User
     */
    @Override
    public Result getAllPermissionsByPageAndSizeAndAnyArgs(int page, int size, Map<String, String> args) {
        GlUtils<Permission, PermissionDao> glUtils = new GlUtils<>();
        return glUtils.getAllByPageAndSizeAndAnyArgs(page,size,args,permissionDao);
    }

    /**
     * 添加权限
     *
     * @param permission 权限
     * @return 添加结果
     */
    @Override
    public Result addPermission(Permission permission) {
        permission.setCreateTime(new Date());
        permission.setCreateUserId(getCurrentUser().getId());
        permission.setUpdateTime(new Date());
        permission.setUpdateUserId(getCurrentUser().getId());
        permission.setDel(false);
        HashSet<Resource> resources = new HashSet<>();
        for (Resource resource:permission.getResources()) {
            Result one = resourceService.getOne(resource.getId());
            if (ResultFactory.isSuccess(one)){
                resources.add((Resource) one.getObject());
            }else {
                return one;
            }
        }
        permission.setResources(resources);
        return save(permission);
    }

    /**
     * @param permission 权限
     * @return 更新权限结果
     * 更新权限
     */
    @Override
    public Result updatePermission(Permission permission) {
        Result result = getOne(permission.getId());
        if (ResultFactory.isSuccess(result)) {
            permission = (Permission) result.getObject();
            permission.setUpdateTime(new Date());
            permission.setUpdateUserId(getCurrentUser().getId());
            return save(permission);
        }else{
            return result;
        }

    }

    /**
     * 批量删除权限
     *
     * @param ids 权限id集合
     * @return 批量删除结果
     */
    @Override
    public Result deletePermission(List<Long> ids) {
        try {
            permissionDao.deleteAllByIdIn(ids);
            return ResultFactory.isSuccess(StaticValue.DELETE_DATA_SUCCESS);
        }catch (Exception e){
            log.error(e.getMessage());
            return ResultFactory.isError(StaticValue.DELETE_DATA_ERROR,e);
        }

    }

    /**
     * 批量添加权限
     *
     * @param permissionList 权限列表
     * @return 添加结果
     */
    @Override
    public Result addAllPermission(List<Permission> permissionList) {
        for(Permission permission:permissionList){
            permission.setCreateTime(new Date());
            permission.setCreateUserId(getCurrentUser().getId());
            permission.setUpdateTime(new Date());
            permission.setUpdateUserId(getCurrentUser().getId());
            permission.setDel(false);
            HashSet<Resource> resources = new HashSet<>();
            for (Resource resource:permission.getResources()) {
                Result one = resourceService.getOne(resource.getId());
                if (ResultFactory.isSuccess(one)){
                    resources.add((Resource) one.getObject());
                }else {
                    return one;
                }
            }
            permission.setResources(resources);
        }
        List<Permission> permissions = permissionDao.saveAll(permissionList);
        try {
            return ResultFactory.isSuccess(StaticValue.SUCCESS_MESSAGE, permissions);
        } catch (Exception e) {
            log.error(e.getMessage());
            return ResultFactory.isError(StaticValue.ERROR_MESSAGE, e);
        }
    }

    /**
     * 更新资源对照
     *
     * @param pid     权限编号
     * @param ridList 资源列表
     * @return 更新结果
     */
    @Override
    public Result updatePermissionResources(long pid, List<Long> ridList) {
        Result one = getOne(pid);
        if (ResultFactory.isSuccess(one)) {
            Permission permission = (Permission) one.getObject();
            Set<Resource> resourceList= new HashSet<>();
            return getResult(ridList, permission, resourceList);
        }
        return one;
    }

    /**
     * 添加资源对照
     *
     * @param pid     权限编号
     * @param ridList 资源列表
     * @return 添加结果
     */
    @Override
    public Result addPermissionResources(long pid, List<Long> ridList) {
        Result one = getOne(pid);
        if (ResultFactory.isSuccess(one)) {
            Permission permission = (Permission) one.getObject();
            Set<Resource> resourceList= permission.getResources();
            return getResult(ridList, permission, resourceList);
        }
        return one;
    }

    private Result getResult(List<Long> ridList, Permission permission, Set<Resource> resourceList) {
        for (Long rid : ridList){
            Result one1 = resourceService.getOne(rid);
            if (ResultFactory.isSuccess(one1)) {
                resourceList.add((Resource) one1.getObject());
            }else {
                return one1;
            }
        }
        permission.setResources(resourceList);
        return updatePermission(permission);
    }

    /**
     * 删除资源对照
     *
     * @param pid     权限编号
     * @param ridList 资源列表
     * @return 删除结果
     */
    @Override
    public Result deletePermissionResources(long pid, List<Long> ridList) {
        Result one = getOne(pid);
        if (ResultFactory.isSuccess(one)) {
            Permission permission = (Permission) one.getObject();
            Set<Resource> resourceList= permission.getResources();
            for (Long rid : ridList){
                Result one1 = resourceService.getOne(rid);
                if (ResultFactory.isSuccess(one1)) {
                    resourceList.remove( one1.getObject());
                }else {
                    return one1;
                }
            }
            permission.setResources(resourceList);
            return updatePermission(permission);
        }
        return one;
    }


}
